package br.com.intelsys.basics.utils;

import javax.activation.MimetypesFileTypeMap;

import org.apache.commons.validator.GenericValidator;

public class MimeTypeExtractor {
	private static final String APPLICATION_OCTET_STREAM = "application/octet-stream";

	private static String getFileExtension(String file) {
		try {
			return file.substring(file.lastIndexOf('.') + 1).toLowerCase();
		} catch (Exception e) {
			return "";
		}
	}

	public static String getContentType(String path) {
		String contentType = new MimetypesFileTypeMap().getContentType(path);
		if (GenericValidator.isBlankOrNull(contentType) || APPLICATION_OCTET_STREAM.equals(contentType)) {
			/*
			if (log.isDebugEnabled()) {
				log.debug("Content-type [not-found]: " + contentType + " -> " + path);
			}
			*/
			contentType = getContentTypeInternal(path);
		}
		/*
		if (log.isDebugEnabled()) {
			log.debug("Content-type: " + contentType + " -> " + path);
		}
		*/
		return contentType;
	}

	private static String getContentTypeInternal(String path) {
		String ext = getFileExtension(path);
		if ("js".equals(ext)) {
			return "text/javascript";
		}
		return APPLICATION_OCTET_STREAM;
	}
}
